<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.rule_id ? $t('编辑') : $t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" width="620px" top="5vh" @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" :inline="true" label-width="130px" :rules="rules" :key="key" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('协议名称')" class="s7300Form" prop="proto">
          <div style="color:#999;width:250px;">{{ rule[record.proto] }}</div>
        </el-form-item>
        <el-form-item :label="$t('动作')" class="s7300Form" prop="action">
          <el-select v-model="record.action" size='small' ref="action" style="width:250px;" filterable>
            <el-option v-for="(value, key) in actionList" :key="key" :label="$t(value)" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('访问类型')" class="s7300Form" prop="access_mode">
          <el-select v-model="record.access_mode" size='small' ref="accessMode" style="width:250px;" filterable>
            <el-option v-for="(value, key) in accessModeList" :key="key" :label="$t(value)" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('寄存器区间')" v-if="record.access_mode === 'absolute_access'" prop="register_interval" key="register_interval">
          <el-select v-model="record.register_interval" class="s7300Length" ref='interval' size='small' filterable>
            <el-option v-for="(value, key) in s7PlusIntervalList" :key="key" :label="$t(value)" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('db值')" prop="db_num" v-if="record.register_interval === '0x8a' && record.access_mode === 'absolute_access'">
          <el-input v-emoji v-model="record.db_num" ref="dbnNum" class="s7300Length" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('读写属性')" class="s7300Form" prop="func">
          <el-select v-model="record.func" size='small' ref="func" style="width:250px;" filterable>
            <el-option v-for="(value, key) in s7PlusFuncList" :key="key" :label="$t(value)" :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('寄存器起始地址')" prop="register_address_min" v-if="record.access_mode === 'absolute_access'" style="margin-right:0">
          <el-input v-emoji v-model="record.register_address_min" ref="min" class="s7300Length" size='small'></el-input>
        </el-form-item>
        <el-form-item label-width="0" v-if="record.access_mode === 'absolute_access'" prop="register_address_min_position">
          {{$t('位')}} <el-select v-model="record.register_address_min_position" ref="character" placeholder="" style="width:70px" size='small'>
            <el-option v-for="val in positionList" :key="val" :label="val" :value="val">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('寄存器结束地址')" prop="register_address_max" v-if="record.access_mode === 'absolute_access'" style="margin-right:0">
          <el-input v-emoji v-model="record.register_address_max" ref="max" class="s7300Length" size='small'></el-input>
        </el-form-item>
        <el-form-item label-width="0" v-if="record.access_mode === 'absolute_access'" prop="register_address_max_position">
          {{$t('位')}} <el-select v-model="record.register_address_max_position" ref="maxPosition" placeholder="" style="width:70px" size='small'>
            <el-option v-for="val in positionList" :key="val" :label="val" :value="val">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="innerAddSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="innerAddClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import ruleArray from '../../ruleArray'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'S7300PlusDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateDbNum = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value)) || !this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 0 || Number(value) > 255) {
        callback(new Error(this.$t('输入范围0~255')))
      } else {
        callback()
      }
    }
    var validateAddress = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (Number(value) < 0 || Number(value) > 8191) {
        callback(new Error(this.$t('输入范围0~8191')))
      } else if (this.record.register_address_min && this.record.register_address_max && (Number(this.record.register_address_min) > Number(this.record.register_address_max))) {
        callback(new Error(this.$t('起始地址必须小于结束地址')))
      } else {
        this.chearRule('register_address_max')
        this.chearRule('register_address_min')
        callback()
      }
    }
    return {
      dialogVisible: false,
      record: {
        access_mode: 'absolute_access',
        action: 'accept',
        db_num: 0,
        func: '0x054c',
        key: '1',
        match_direction: '-',
        proto: 's7_300_plus',
        register_address_max: 0,
        register_address_min: 0,
        register_address_max_position: 0,
        register_address_min_position: 0,
        register_interval: '0x50',
        rule_id: null
      },
      recordCopy: {
        access_mode: 'absolute_access',
        action: 'accept',
        db_num: 0,
        func: '0x054c',
        match_direction: '-',
        proto: 's7_300_plus',
        register_address_max: 0,
        register_address_min: 0,
        register_address_max_position: 0,
        register_address_min_position: 0,
        register_interval: '0x50',
        rule_id: null
      },
      rule: ruleArray.ruleShow,
      s7PlusFuncList: ruleArray.s7PlusFuncList,
      s7PlusIntervalList: ruleArray.s7PlusIntervalList,
      actionList: { 'accept': '允许', 'alert': '告警' },
      accessModeList: { 'absolute_access': '绝对访问', 'character_access': '字符访问' },
      positionList: [0, 1, 2, 3, 4, 5, 6, 7],
      rules: {
        db_num: [{ required: false, validator: validateDbNum, trigger: 'blur' }],
        register_address_max: [{ required: false, validator: validateAddress, trigger: 'blur' }],
        register_address_min: [{ required: false, validator: validateAddress, trigger: 'blur' }],
        register_interval: [{ required: false, validator: validateName, trigger: 'change' }]
      }
    }
  },
  computed: {
    change () {
      const { register_interval, access_mode } = this.record
      return { register_interval, access_mode }
    }
  },
  watch: {
    change (val) {
      if (val.access_mode === 'character_access') {
        this.key = this.key + 1
        this.$nextTick(() => {
          const data = ['min', 'max']
          console.log(this.$refs.character)
          const selectData = ['action', 'accessMode', 'interval', 'func', 'maxPosition', 'character']
          selectClass(this.$refs, selectData)
          inputClass(this.$refs, data)
        })
        if (val.register_interval === '0x8a') {
          this.$nextTick(() => {
            const data = ['dbnNum']
            inputClass(this.$refs, data)
          })
        }
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const selectData = ['action', 'accessMode', 'func']
        selectClass(this.$refs, selectData)
      })
      if (data) {
        this.record = Object.assign(this.record, data)
      }
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.record))
          this.$emit('addConfigRuleMap', formData)
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.$emit('childrenClose')
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.resetFields()
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    },
    chearRule (name) {
      if (!isNaN(Number(this.record[name])) && this.isInteger(this.record[name]) && (Number(this.record[name]) >= 0 && Number(this.record[name]) <= 65535)) {
        this.$refs['form'].clearValidate([name])
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.s7300Form {
  width: 400px;
}

.s7300Length {
  width: 250px;
}
</style>
